//
//  SocketDispatch.m
//  dongfangyixin20151027
//
//  Created by longziyuan on 15-3-9.
//
//

#import "SocketDispatch.h"
#import "Infro.h"
#import "GlobalVar.h"
static SocketDispatch* shareInstance=nil;


@implementation SocketDispatch

+(SocketDispatch*)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareInstance=[[self alloc]init];
    });
    
    
    return shareInstance;
}





-(void)socketCheck
{
    timeArr=[[NSMutableArray alloc]init];
  
    NSArray* theArr=[GlobalVar getZhongzhuanUrls];
    
    
    urlsDic=[[NSMutableDictionary alloc]init];
    if ([theArr count]>0) {
        for (NSString* url in theArr) {
            url=[url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            NSArray* componentArr=[url componentsSeparatedByString:@"/"];
            NSString* urlMainPart=componentArr[2];
            [urlsDic setObject:url forKey:urlMainPart];
        }
        
    }else
    {
        
        [urlsDic setObject:@"http://122.114.120.26/sync" forKey:@"122.114.120.26:80"];
        [urlsDic setObject:@"http://59.63.182.181:8008" forKey:@"59.63.182.181:8008"];
        [urlsDic setObject:@"http://171.34.30.181:8008" forKey:@"171.34.30.181:8008"];
        [urlsDic setObject:@"http://61.146.138.151:8002/appapi" forKey:@"61.146.138.151:8002"];
        [urlsDic setObject:@"http://121.40.86.219:8002/appapi" forKey:@"121.40.86.219:8002"];
        [urlsDic setObject:@"http://119.147.137.16:8002/appapi" forKey:@"119.147.137.16:8002"];
        [urlsDic setObject:@"http://119.147.137.79:8002/appapi" forKey:@"119.147.137.79:8002"];
        [urlsDic setObject:@"http://183.237.48.232:8002/appapi" forKey:@"183.237.48.232:8002"];
        [urlsDic setObject:@"http://61.145.116.124:8008/appapi" forKey:@"61.145.116.124:8008"];
        [urlsDic setObject:@"http://122.114.58.59:8002/appapi" forKey:@"122.114.58.59:8002"];
        [urlsDic setObject:@"http://222.180.162.61:8008/appapi" forKey:@"222.180.162.61:8008"];
        [urlsDic setObject:@"http://113.207.26.202:8008/appapi" forKey:@"113.207.26.202:8008"];
      
    }
 
   
    
    
    
    
    
    is_Lock=YES;
    theCount=0;
    for (int i=0; i<[[urlsDic allKeys] count]; i++) {
        Infro* info=[[Infro alloc]init];
        
        NSString* ipAndPort=[[urlsDic allKeys] objectAtIndex:i];
        NSArray* ipAndPortArr=[ipAndPort componentsSeparatedByString:@":"];
        
        
        UInt64 pre=[GlobalVar getTimeChuo];
        
        info.theIP=ipAndPort;
        info.starTime=pre;
        NSLog(@"请求之前的时间:%llu,对应的:%@",info.starTime,ipAndPort);
        
        [timeArr addObject:info];
        
      
        
        @try {
            AsyncSocket*  socket=[[AsyncSocket alloc] initWithDelegate:self];
            [socket connectToHost:ipAndPortArr[0] onPort:[[ipAndPortArr objectAtIndex:1] intValue]error:nil];
            
            [socket readDataWithTimeout:30.0 tag:1];
        }
        @catch (NSException *exception) {
            NSLog(@"the exception:%@",exception);
        }
        @finally {
            NSLog(@"go on");
        }
        
        
        
    }
    
   /* NSString* bestUrl=nil;

    while (true) {
        bestUrl=[[NSUserDefaults standardUserDefaults] objectForKey:@"BEST"];
        if (bestUrl==nil && theCount<[[urlsDic allKeys] count]) {
            sleep(50);
        }else
        {
            return bestUrl;
        }
    
    }*/
    

}

-(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    
    
    
    
    
    
    
    
    
    
    
    NSString* backIPAndPort=[NSString stringWithFormat:@"%@:%hu",host,port];
    NSLog(@"已经连接到:%@",backIPAndPort);
    theCount+=1;
    
    
    
    
    
    for (Infro* inf in timeArr) {
        if ([inf.theIP isEqualToString:backIPAndPort]) {
            
            
            

           // NSLog(@"开始时间:%llu",inf.starTime);
            
            UInt64 after=[GlobalVar getTimeChuo];
            
            inf.endTime=after;
            NSLog(@"结束时间:%llu",inf.endTime);
            
            
            
            
            
            
            
            
            
            
            
            
            
            UInt64 cha=[GlobalVar preRequestTime:inf.starTime  AndAfterRequestTime:after];
            
            NSLog(@"差值:%llu",cha);
            
            
            
            
            
            
            NSString* result=[NSString stringWithFormat:@"%@|%llu\n",inf.theIP,cha];
            
            
            NSLog(@"结果是:%@",result);
            
           [GlobalVar writeTheInfoToTheLocal:result];
            
            
            
        }
    }
    
    
    if (is_Lock==YES) {
        is_Lock=NO;
        
        NSString* zuiyouUrl=[NSString stringWithFormat:@"%@:%hu",host,port];
        
        
        
       
            NSString* theUl=[urlsDic objectForKey:zuiyouUrl];
            NSLog(@"最好的url:%@",theUl);
                
                
                
                
                NSString* theBestResult=[NSString stringWithFormat:@"#%@ \n",theUl];
                [GlobalVar writeTheInfoToTheLocal:theBestResult];
                
                
                
                
                
                NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
                [defaults setObject:theUl forKey:@"BEST"];
                [defaults synchronize];

        
        }
        
        
        
        
        
        
        
    
    

    
    
    [sock disconnect];
}


-(void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    NSLog(@"did disconnect to host");
}

-(void)dealloc
{

    [urlsDic release];
    [super dealloc];
}
@end
